package com.chen.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.chen.model.entity.pay.PaymentInfo;
import com.chen.model.vo.common.ResultCodeEnum;
import com.chen.pay.properties.AlipayProperties;
import com.chen.pay.service.PayService;
import com.chen.pay.service.PaymentInfoService;
import com.chen.service.exception.MyException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * @author cgj
 * @date 5/4/25 10:55 AM
 */
@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayProperties alipayProperties;

    /**
     * 支付宝支付
     *
     * @param orderNo
     * @return
     */
    @SneakyThrows  // try --cache 声明式的 ,不用打乱代码结构, lombok提供的
    @Override
    public String submitAlipay(String orderNo) {
        // 保存到记账本
        PaymentInfo paymentInfo = paymentInfoService.savaPaymentInfo(orderNo);
        // 初始化SDK
//创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();

        // 同步回调
        alipayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());

        // 异步回调
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());

        // 准备请求参数 ，声明一个map 集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code", "QUICK_WAP_WAY");
        //map.put("total_amount",paymentInfo.getAmount());
        map.put("total_amount", new BigDecimal("0.01"));
        map.put("subject", paymentInfo.getContent());
        alipayRequest.setBizContent(JSON.toJSONString(map));

        // 发送请求
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            System.out.println(response.getBody());
            return response.getBody();
        } else {
            System.out.println("调用失败");
            throw new MyException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
